package org.fatmansoft.teach.controllers.ViewController;

import org.fatmansoft.teach.Repository.ViewRepository.CourseRepository;
import org.fatmansoft.teach.Repository.ViewRepository.StudentCourseRepository;
import org.fatmansoft.teach.Repository.ViewRepository.StudentRepository;
import org.fatmansoft.teach.entity.ViewEntity.Course;
import org.fatmansoft.teach.entity.ViewEntity.Student;
import org.fatmansoft.teach.entity.ViewEntity.StudentCourse;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/studentCourse")
public class StudentCourseController {
    @Autowired
    StudentCourseRepository studentCourseRepository;

    @Autowired
    StudentRepository studentRepository;

    @Autowired
    CourseRepository courseRepository;

    @PostMapping("/getInfo")
    public DataResponse getInfo(@Valid @RequestBody DataRequest request) {
        Map<String, Object> map = new HashMap<>();

        int currentPage = 1;  //分页页码
        String RequestCurPage = Utils.parseRequest(request, "currentPage", map);  //获取解析的数据
        if (RequestCurPage != null & Utils.checkNum(RequestCurPage)) {  //要求数据不为空，且为纯数字
            currentPage = Integer.parseInt(RequestCurPage);
        }

        Integer studentNum = -1;  //学号
        String RequestCouNum = Utils.parseRequest(request, "studentNum", map);  //获取解析的数据
        if (RequestCouNum != null) {  //要求数据不为空
            studentNum = Integer.parseInt(RequestCouNum);
        }

        List<StudentCourse> studentCourseList = null;  //创建选课列表，用于返回前端
        if (RequestCouNum != null) {  //按照学号查询
            studentCourseList = studentCourseRepository.findStudentCourseByStudentId(studentNum);
        } else {  //不按照学号查询
            studentCourseList = studentCourseRepository.findAll(PageRequest.of(currentPage - 1, 5)).toList();
        }

        List<Student> studentList = studentRepository.findAll().subList(0, studentRepository.findAll().size());
        List<Course> courseList = courseRepository.findAll().subList(0, courseRepository.findAll().size());
        map.put("tableData", studentCourseList);
        map.put("studentList", studentList);
        map.put("courseList", courseList);
        map.put("total", studentCourseRepository.findAll().size());

        return new DataResponse("0", map);
    }

    @PostMapping("/deleteInfo")
    public DataResponse delete(@Valid @RequestBody DataRequest request) {
        Map<String, Object> map = new HashMap<>();

        String deleteId = Utils.parseRequest(request, "deleteId", map);
        if (Utils.checkNum(deleteId)) {
            studentCourseRepository.deleteById(Integer.parseInt(deleteId));
        }

        return new DataResponse("0", map);
    }

    @PostMapping("/updateAndCreateInfo")
    public DataResponse updateAndCreate(@Valid @RequestBody DataRequest request) {
        Map<String, Object> map = new HashMap<>();
        String code;

//        从前端获取formData转化为Map
        Map formData = (Map) request.getData().get("formData");
        StudentCourse studentCourse = new StudentCourse();

        if (formData.get("id") != null) studentCourse.setId(Integer.parseInt(formData.get("id").toString()));
        else {  //如果没有传入id->查找数据库，补全ID
            int lastRecord = courseRepository.findAll().size() - 1;
            int lastId = courseRepository.findAll().get(lastRecord).getId();
            studentCourse.setId(lastId + 1);
        }
        if (formData.get("studentId") != null) {  //获取学生的方法
            Student student = new Student();
            if (studentRepository.findById((int) Long.parseLong(formData.get("studentId").toString())).isPresent()) {
                student = studentRepository.findById((int) Long.parseLong(formData.get("studentId").toString())).get();
            }
            studentCourse.setStudent(student);
        }
        if (formData.get("courseId") != null) {  //获取课程的方法
            Course course = new Course();
            if (courseRepository.findById((int) Long.parseLong(formData.get("courseId").toString())).isPresent()) {
                course = courseRepository.findById((int) Long.parseLong(formData.get("courseId").toString())).get();
            }
            studentCourse.setCourse(course);
        }
        if (formData.get("usualScore") != null)
            studentCourse.setUsualScore(Double.valueOf(formData.get("usualScore").toString()));
        if (formData.get("finalScore") != null)
            studentCourse.setFinalScore(Double.valueOf(formData.get("finalScore").toString()));
        if (formData.get("totalScore") != null) {
            studentCourse.setTotalScore(Double.valueOf(formData.get("totalScore").toString()));
            //设置绩点为小数点后一位
            DecimalFormat d=new DecimalFormat("#.0");
            studentCourse.setGpa(Double.parseDouble(d.format((Double.parseDouble(formData.get("totalScore").toString()) / 10) - 5)));
        }

//        判断当前元组是否已经存在（根据ID是否存在)
        if (studentCourseRepository.findById(studentCourse.getId()).isPresent()) {  //查看id是否已经存在
            code = "0"; //表示更新
        } else {
            code = "1"; //表示新增
        }

        studentCourseRepository.save(studentCourse);  //更新/保存的数据

        return new DataResponse(code, map);
    }

}

